﻿using AlarmPlatformInterface.DMs;
using Entity.Models;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Asn1.Crmf;
using RestSharp;
using StackExchange.Redis;
using System.Runtime.Intrinsics.Arm;
using Utility;

namespace AlarmPlatformInterface.Comm
{
    public class Global
    {
        public static IConfiguration Configuration { get; set; }


        public static bool ValidateToken(ref ReqBaseModel bModel, ref string newToken, ref OperatorInfo uinfo)
        {
            bool result = false;
            try
            {
                string sign = Utility.Security.Sign(bModel.Parameters, bModel.Token);
                if (sign != bModel.Sign)
                {
                    WriteLog.WriteExceptionFile($"页面传输数据异常：{bModel.SerializerObjectToString()}");
                    return false;
                }

                string parameters = bModel.Parameters.Decrypt($"H{bModel.Token.Substring(6, 3)}{bModel.Token.Substring(68, 3)}T");
                bModel.Parameters = parameters;

                string temp = Extensions.DesDecrypt(bModel.Token, Global.Configuration["AppSettings:CryptKey"]);
                string[] arr = temp.Split("|");
                if (arr.Length != 3)
                {
                    return result;
                }
                int day = Convert.ToInt32(Global.Configuration["AppSettings:ExpireDay"]);

                DateTime now = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                DateTime dt = Convert.ToDateTime(new DateTime(Convert.ToInt32(arr[2].Substring(0, 4)), Convert.ToInt32(arr[2].Substring(4, 2)), Convert.ToInt32(arr[2].Substring(6, 2)), Convert.ToInt32(arr[2].Substring(8, 2)), Convert.ToInt32(arr[2].Substring(10, 2)), Convert.ToInt32(arr[2].Substring(12, 2))));
                DateTime expire = Convert.ToDateTime(now.AddDays(-day).ToString("yyyy-MM-dd"));
                if (dt < expire || dt > now)
                {
                    return result;
                }
                using (Entity.DBContext context = Entity.BaseContext.CreateContext(Global.Configuration["ConnectionStrings:DDb"]))
                {
                    if (parameters.StartsWith('{') && parameters.EndsWith('}'))
                    {
                        JObject ob = JObject.Parse(parameters);
                        JToken jt = ob as JToken;
                        var reader = jt.CreateReader();
                        while (reader.Read())
                        {
                            if (reader.Value != null)
                            {
                                if (reader.TokenType != JsonToken.PropertyName)
                                {
                                    if (reader.Value.ToString().ToLower().Contains("select")
                                        || reader.Value.ToString().ToLower().Contains("insert")
                                        || reader.Value.ToString().ToLower().Contains("delete")
                                        || reader.Value.ToString().ToLower().Contains("update")
                                        || reader.Value.ToString().ToLower().Contains("drop")
                                        || reader.Value.ToString().ToLower().Contains("truncate")
                                        || reader.Value.ToString().ToLower().Contains("declare")
                                        || reader.Value.ToString().ToLower().Contains("union")
                                        || reader.Value.ToString().ToLower().Contains("and"))
                                    {
                                        uinfo = context.operatorInfos.Where(p => p.LoginName == arr[0] && p.Password == arr[1]).FirstOrDefault();
                                        if (uinfo != null)
                                        {
                                            uinfo.LimitLogin = 1;
                                            context.Update(uinfo);
                                            context.SaveChanges();
                                        }
                                        WriteLog.WriteExceptionFile($"页面传输数据异常：{bModel.SerializerObjectToString()}");
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                    uinfo = context.operatorInfos.Where(p => p.LoginName == arr[0] && p.Password == arr[1] && p.LimitLogin != 1).FirstOrDefault();
                    if (uinfo != null)
                    {
                        result = true;
                        newToken = Extensions.DesEncrypt(uinfo.LoginName + "|" + uinfo.Password + "|" + DateTime.Now.ToString("yyyyMMddHHmmssff"), Global.Configuration["AppSettings:CryptKey"]);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteExceptionFile("Validate Token : " + ex.Message + "\r\n" + ex.StackTrace);
                result = false;
            }
            return result;
        }

    }
}
